package org.dxy.domain.handler.workstation;

import com.google.common.eventbus.EventBus;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dxy.domain.command.workstation.WorkstationInCommand;
import org.dxy.domain.event.DomainEvent;
import org.dxy.domain.model.aggregate.Workstation;
import org.dxy.domain.handler.CommandHandler;
import org.dxy.domain.port.repository.IWorkstationRepository;
import org.dxy.types.common.CommandResult;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @description: 工位进站命令处理器
 * @author: dxy
 * @createTime: 2025/10/13
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class WorkstationInCommandHandler implements CommandHandler<WorkstationInCommand, Void> {

    private final IWorkstationRepository workstationRepository;
    private final EventBus eventBus;

    @Transactional
    @Override
    public CommandResult<Void> handle(WorkstationInCommand command) {
        try {
            log.info("开始处理工位进站命令: command: {}", command);

//            // 1. 检查产品序列号是否已在其他工位进行操作
//            if (workstationRepository.existsActiveBySerialNumber(command.serialNumber())) {
//                return CommandResult.fail(null, "产品序列号已在其他工位进行操作: " + command.serialNumber());
//            }

            Workstation workstation = workstationRepository.findById(command.workstationId());

            // 4. 执行进站操作
            workstation.stationIn(command);

            // 5. 更新聚合
            workstationRepository.update(workstation);

            // 6. 获取并发布领域事件
            List<DomainEvent> events = workstation.getDomainEvents();
            for (DomainEvent event : events) {
                log.info("发布领域事件: {}", event.getClass().getSimpleName());
                eventBus.post(event);
            }

            // 7. 清除已发布的事件
            workstation.clearDomainEvents();

            log.info("工位进站命令处理完成: command: {}", command);
            return CommandResult.success("工位进站成功");

        } catch (Exception e) {
            log.error("工位进站失败: command: {}", command, e);
            return CommandResult.fail( "工位进站失败: " + e.getMessage());
        }
    }
}